<?php
require(dirname(__FILE__) .'/config.inc');
require(ROOT .'/misc/functions.inc');
require(ROOT .'/includs.inc');

$tr = tree::getInstance();
$c  = config::read('categories', 'seo');

if(!empty($c))
{
   $cat = array();
   foreach ($c AS $id)
   {
      $cat[] = $id;
      if(($node = $tr->getNode($id)) != false)
      {
         $nc = $tr->getChildrenId($id);
         if(!empty($nc))
         {
            $cat = array_merge($cat, $nc);
         }
      }
   }
   
   $DB->sql = 'SELECT `id`, `mdate`, `cat` 
      FROM `meccano_articles` 
      WHERE `active` = "1" AND `deleted` IS NULL AND `cat` IN ('. join(',', $cat) .')';
   $tmp     = $DB->DB_Fetch();
   $articles = array();

   if(!empty($tmp))
   {
      for($i=0, $t=sizeof($tmp); $i<$t; $i++)
      {
         $articles[$tmp[$i]['cat']][] = array(
            'id' => $tmp[$i]['id'],
            'date' => $tmp[$i]['mdate']
         );
      }
   }
   
   header ("Content-Type:text/xml"); 
   echo '<?xml version="1.0" encoding="UTF-8"?>'. EOL;
   echo '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">'. EOL;
   
   // BUILD URLS
   
   foreach($cat AS $id)
   {
      $node = $tr->getNode($id);
      
      echo '<url>'. EOL;
      echo '<loc>http://'. config::read('domain', 'file') . $node->href .'</loc>'. EOL;
      echo '<lastmod>'. $node->mdate .'</lastmod>'. EOL;
      echo '</url>'. EOL;
      
      if(!empty($articles[$node->id]) && sizeof($articles[$node->id]) > 1)
      {
         foreach($articles[$node->id] AS $a)
         {
            echo '<url>'. EOL;
            echo '<loc>http://'. config::read('domain', 'file') . $node->url . $a['id'] .'.html</loc>'. EOL;
            echo '<lastmod>'. $a['date'] .'</lastmod>'. EOL;
            echo '</url>'. EOL;
         }
      }
   }
   
   echo '</urlset>';
}


/*
<url>
   <loc>http://www.example.com/</loc>
   <lastmod>2005-01-01</lastmod>
   <changefreq>monthly</changefreq>
   <priority>0.8</priority>
</url>
 */